# -*- coding:utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from process_bar import ProgressBar
from get_proxy import get_proxy
from multiprocessing import Process, Pool, Lock
import datetime
import sys
import requests
import json
import re

key_words = [u'面膜', u'洗面奶', u'花露水', u'化妆棉', u'眼霜', u'杏仁', u'饼干', u'薯片', u'麦片', u'牛肉干', u'巧克力', u'红酒',
             u'伏特加', u'金酒', u'茅台', u'啤酒', u'牛奶', u'鸡蛋', u'猪肋骨', u'鱼', u'土鸡', u'牛排', u'苹果', u'橙子', u'速冻水饺',
             u'NFC果汁', u'玉米油', u'米', u'盐', u'糖', u'酱油', u'醋', u'卷纸', u'抽纸', u'沐浴露', u'洗发水', u'洗洁精', u'洗衣粉',
             u'香皂', u'保鲜膜', u'保鲜袋', u'卫生巾', u'牙膏', u'牙刷', u'毛巾']
file_out = None


def search_key_word(driver, key_word, index):
    global file_out
    process_bar = None
    elem_search = driver.find_element_by_name('q')
    elem_search.clear()
    elem_search.send_keys(key_word)
    elem_search.send_keys(Keys.RETURN)
    while True:
        if driver.title == u'理想生活上天猫':
            iframe = driver.find_element_by_tag_name('iframe')
            driver.switch_to_frame(iframe)
            elem_switch = driver.find_element_by_class_name('login-switch')
            elem_switch.click()
            elem_name = driver.find_element_by_name('TPL_username')
            elem_name.clear()
            elem_name.send_keys(u'xxx')
            elem_password = driver.find_element_by_name('TPL_password')
            elem_password.clear()
            elem_password.send_keys('xxx')
            elem_login = driver.find_element_by_id('J_SubmitStatic')
            elem_login.click()
            driver.implicitly_wait(2)
        elif u'-天猫Tmall.com-理想生活上天猫' not in driver.title:
            wait = WebDriverWait(driver, 3600 * 24)
            element = driver.find_element_by_tag_name('div')
            ActionChains(driver).context_click(element).perform()
            elem = wait.until(EC.title_contains(u'-天猫Tmall.com-理想生活上天猫'))
        elem_list = driver.find_element_by_id('J_ItemList')
        elem_products = elem_list.find_elements_by_class_name('product')
        for elem_product in elem_products:
            try:
                sku_id = elem_product.get_attribute('data-id')
                if sku_id is None:
                    continue
                file_out.write(','.join([key_word, str(sku_id), str(index)]) + '\n')
                print [key_word, str(sku_id), str(index)]
            except Exception, e:
                print e.message
                print elem_product.get_attribute('data-id')
        elem_page_info = driver.find_element_by_class_name('ui-page-s-len').text.split('/')
        if len(elem_page_info) == 2:
            if process_bar is None:
                process_bar = ProgressBar(count=int(elem_page_info[0]), total=int(elem_page_info[1]))
            else:
                process_bar.move()
            print '\n'
            process_bar.log()
            print '\n'
            if elem_page_info[0] == elem_page_info[1]:
                break
        elif len(elem_page_info) == 1:
            break
        elem = driver.find_element_by_class_name('ui-page-next')
        elem.click()


if __name__ == '__main__':
    reload(sys)
    sys.setdefaultencoding('gbk')
    file_out = open('../data/ID_TMALL.csv', 'w')

    init_driver = webdriver.Chrome()
    init_driver.get('http://www.tmall.com')
    init_driver.maximize_window()
    for index, key in enumerate(key_words):
        search_key_word(init_driver, key, index)
    init_driver.quit()
    file_out.close()
